package com.example.ymm.modules1.controller.sys;

import com.example.ymm.annotation.RequestLimiter;
import com.example.ymm.model.CommonResult;
import com.example.ymm.model.UserLoginParam;
import com.example.ymm.modules1.controller.BaseController;
import com.example.ymm.modules1.service.sys.SysUserService;
import com.example.ymm.modules1.service.user.DbUserService;
import com.example.ymm.util.RedisKeyManager;
import com.example.ymm.util.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.LinkedHashMap;
import java.util.Map;

@RestController
@RequestMapping("/hl/sys/userLogin")
@Api(tags = "pc端登录接口")
@Slf4j
@CrossOrigin
public class SysLoginController extends BaseController {
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    DbUserService dbUserService;

    @ApiOperation(value = "pc端登录")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public CommonResult login(@Valid  UserLoginParam umsAdminLoginParam) {
        try {
//            return dbUserService.loginByUserId("2363192520970306");
            return sysUserService.login(umsAdminLoginParam);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }


    }


    @ApiOperation(value = "pc端退出登录")
    @RequestLimiter(QPS = 1D)
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    public CommonResult logout(HttpServletRequest request) {
        try {
            String authHeader = request.getHeader(this.tokenHeader);
            if (authHeader != null && authHeader.startsWith(this.tokenHead)) {
                String authToken = authHeader.substring(this.tokenHead.length());// The part after "Bearer "
                redisUtil.remove(RedisKeyManager.pc_token_key + authToken);
            }
            return CommonResult.success();
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }


    }



}
